/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ttt.nor2.thread;

import com.ttt.nor2.config.Config;
import com.ttt.nor2.config.RtnBilling;
import com.ttt.nor2.db.DBMysql;
import com.ttt.nor2.importdata.txt.ImportFile;
import com.ttt.nor2.util.ExceptionUtil;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import org.apache.log4j.Logger;

/**
 *
 * @author Administrator
 */
public class ThImportBilling extends Thread {

    private Logger log = Logger.getLogger(ThImportBilling.class);
    private Config cfg;
    private String fname;
    private static int thWork = 1;
    private Connection conn;
    private Class c = null;
    private ImportFile iptf = null;

    public static int getThWork() {
        return thWork;
    }

    private synchronized void incThread() {
        thWork++;
    }

    private synchronized void decThread() {
        thWork--;
    }
    public ThImportBilling(Config cfg) {
        this.cfg = cfg;
        fname = cfg.getPathProcess() + cfg.getFilename();
        incThread();
        log.debug("Thread working...[" + thWork + "]");
        //this.conn = DBMysql.getConnection(cfg.getFileprop(), Integer.toString(thWork));
        this.conn = DBMysql.dbConn(cfg.getUrl(), cfg.getUsr(), cfg.getPwd(), cfg.getDb());
        log.info("Connection db name  success...");
    }

    @Override
    public void run() {
        try {
            log.info("Load file name " + fname + " into class " + cfg.getClassname());


            int k = 0;
            FileInputStream fis = new FileInputStream(fname);
            ByteArrayOutputStream aos = new ByteArrayOutputStream();
            
            //int rowsave = 0;
            RtnBilling rtnBuff = new RtnBilling();
            int numrow = 1;
            while ((k = fis.read()) != -1) { // read file

                if (k == 10) { // 1 line charector \n

                    String line = new String(aos.toByteArray(), "TIS-620");
                    // run debug find int charector

                    for (int j = 0; j < line.length(); j++) {
                        log.debug(" converse charecter[" + j + "] : [" + (int) line.charAt(j) + "]");
                    }

                    log.info("Read line from " + fname + " str[" + line + "]");
                    
                    c = Class.forName("com.ttt.nor2.importdata.txt." + cfg.getClassname());
                    iptf = (ImportFile) c.newInstance();
                    iptf.setRow(numrow);//set row
                    iptf.setLine(line); // send string into class
                    iptf.setSplit(cfg.getChSplit()); // send charector split
                    iptf.interpret(); // manage split string line
                    if (!cfg.getClassname().equalsIgnoreCase("Import4CS")) {
                        switch (numrow) {
                            case 1:
                                //$iptf.setFileUpload(fname); // get value year & mon
                                iptf.setRow1();
                                rtnBuff.setYear(iptf.getRtn().getYear());
                                rtnBuff.setMon(iptf.getRtn().getMon());
                                rtnBuff.setStatus(iptf.getRtn().getStatus());
                                rtnBuff.setIndexMonth(iptf.getRtn().getIndexMonth());
                                break;
                            case 2:
                                //iptf.setFileUpload(fname); // get value year & mon
                                iptf.setRow2();
                                rtnBuff.setArrMonth(iptf.getRtn().getArrMonth());
                                break;
                            default:
                                iptf.setRtn(rtnBuff);
                                break;
                        }
                    }
                    
                    iptf.setConn(conn); // set connection into class
                    iptf.savedata();// exec
                    //iptf.start();
                    numrow++;
                    aos.reset();// reset buffer
                } else {// command end read one line
                    log.debug("read value from file : [" + k + "]");
                    aos.write(k);
                }



            }// end read file
            // clear data for end file;
            
            fis.close();// close file
            //move file
            File sf = new File(fname);
            File df = new File(cfg.getPathSuccess() + cfg.getFilename());
            sf.renameTo(df);
            log.info("Move file  :[" + fname + "] =>[" + cfg.getPathSuccess() + cfg.getFilename() + "]");
        } catch (Exception e) {
            log.error("Exception " + ExceptionUtil.getStackTrace(e));
        }
    }// end function run

    @Override
    protected void finalize() throws Throwable {

        try {
            conn.close();
            log.info("Close db " + conn.getCatalog() + " ...");
        } catch (Exception e) {
            log.error("Exception close connectioin error " + ExceptionUtil.getStackTrace(e));
        }

        //log.debug("Set row = 1");
        //iptf.setRow(1);// cleare row == 1
        log.debug("Thread end working...[" + thWork + "]");
        decThread();

    }
}
